package org.example;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Stack;

 class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
  }


public class Test1 {
    //leetcode 145 二叉树的后序遍历 https://leetcode.cn/problems/binary-tree-postorder-traversal/description/

    /**
     * 因为前序遍历的顺序是中左右，后序遍历的顺序为左右中，我们只需要让ret中存储的结点的顺序是中右左，然后将ret逆置就可以了
     * 因为使用的是栈，所以先将中间结点添加进去，然后是左边结点，最后是右边结点
     * @param root
     * @return
     */
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> ret = new ArrayList<>();
        if (root == null) return ret;
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);
        while (!stack.isEmpty()){
            TreeNode node = stack.pop();
            ret.add(node.val);
            if (node.left != null){
                stack.push(node.left);
            }
            if (node.right != null){
                stack.push(node.right);
            }
        }
        Collections.reverse(ret);
        return ret;
    }
}
